package com.freeman.cement.interceptor;

import com.alibaba.fastjson.JSON;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.util.JwtUtil;
import com.freeman.cement.entity.ResultObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取我们请求头中的token验证字符
        String token = request.getHeader("token");
        // 如果请求头中没有token的话，从参数中获取
        if (token == null)
            token = request.getParameter("token");
        if (token == null) {
            // 如果token不存在的话,返回错误信息。
            System.out.println("访问错误，无token");
            throw new AppException(AppExceptionCodeMsg.TOKEN_NOT_EXISTS);
        } else {
            try {
                // 对token进行更新与验证
                //token = JwtUtil.updateToken(token);

                // 对token只进行验证
                //if (JwtUtil.verify(token) != null) {
                //    return true;
                //}

                Claims claims = JwtUtil.verify(token);
                if (claims != null) {
                    if(claims.containsKey("userRole") && claims.get("userRole") != null) {
                        //把变量放在request请求域中，仅可以被这次请求，即同一个request使用
                        request.setAttribute("userRole", claims.get("userRole"));
                        // 添加用户ID到request
                        if(claims.containsKey("userId")) {
                            try {
                                String userId = claims.get("userId").toString();
                                request.setAttribute("userId", Integer.valueOf(userId));
                            } catch (NumberFormatException e) {
                                System.out.println("userId转换失败: " + claims.get("userId"));
                                throw new AppException(AppExceptionCodeMsg.INVALID_TOKEN);
                            }
                        }
                    }
                    return true;
                }
            } catch (Exception e) {
                System.out.println("token验证错误");
                throw new AppException(AppExceptionCodeMsg.INVALID_TOKEN);
            }
        }
        return false;
    }

    /*public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ResultObject ro = null;
        // 获取我们请求头中的token验证字符
        String token = request.getHeader("token");
        // 如果请求头中没有token的话，从参数中获取
        if(token == null)
            token = request.getParameter("token");

        if (token == null)
        {
            // 如果token不存在的话,返回错误信息。
            ro = new ResultObject();
            ro.setCode(1000);
            ro.setMsg("访问错误，无token");
            ro.setData("");
            System.out.println("访问错误，无token");
        }else{
            try {
                // 对token进行更新与验证
                //token = JwtUtil.updateToken(token);

                // 对token只进行验证
                if(JwtUtil.verify(token) != null)
                {
                    ro = null;
                }
            } catch (Exception e) {
                ro = new ResultObject();
                ro.setCode(1000);
                ro.setMsg("token验证错误");
                ro.setData("");
                System.out.println("token验证错误");
            }
        }
        if(ro != null) {//如果有错误信息
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ro));
            return false;
        }else {

            // 将新token加入返回页面的header 配合JwtUtil.updateToken(token);使用
            //response.setHeader("token", token);

            return true;
        }

    }*/


}
